package com.example.chat.navigation

import androidx.navigation.NavHostController
import androidx.navigation.NavOptionsBuilder
import com.example.featuresdk.navigation.INavigationController

/**
 * Utility controller to manage navigation in one central place
 */
class NavigationController : INavigationController {

    private constructor()
    var navController: NavHostController? = null
        internal set

    companion object{
        val instance = NavigationController()
    }

    override fun navigate(route: String, vararg params: String, builder: NavOptionsBuilder.() -> Unit) {

        //Log.e("$this", "route=$route")
        Screen.values().lastOrNull { it.route == route }?.let {
            navigate(it, *params){ builder() }
        }
    }

    override fun back(){
        //Log.e("$this","currentBackStackEntry=${navController?.currentBackStackEntry?.destination?.route}")
        navController?.currentBackStackEntry?.destination?.route.let {
            if(it == Screen.TopicDetail.route){
                navController?.popBackStack(Screen.TopicList.route,inclusive = false)
            }else{
                navController?.popBackStack()
            }
        }
    }

    override fun getNavigationRoutes(): List<String> {
        return Screen.values().map {
            it.route
        }
    }

    fun navigate(screen: Screen, vararg params: String, builder: NavOptionsBuilder.() -> Unit = {launchSingleTop = true}) {

        //Log.e("$this", "screen=$screen")

        when(screen){
/*
            Screen.TopicDetailExternal ->
                navController?.navigate(screen.route.replace("{id}",params[0])){
                    //current back stack: contact list -> [contact detail (Message)]
                    popUpTo(Screen.ContactDetail.route){
                        inclusive = true
                    }
                    launchSingleTop = true
                    //current back stack: contact list -> topic detail
                }
 */
            Screen.TopicDetail ->
                navController?.navigate(screen.route.replace("{id}",params[0])){
                    builder()
                }

            Screen.TopicSetting ->
                navController?.navigate(screen.route.replace("{id}",params[0]))

            else ->
                navController?.navigate(screen.route){
                    builder()
                }
        }
    }
}